package com.kt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kt.pojo.Clubs;
import com.kt.pojo.Players;
import com.kt.service.ClubsService;
import com.kt.service.PlayersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 吴阳基
 * @datetime 2024/2/18 16:19
 */
@Controller
@RequestMapping("/players")
public class PlayersController {
    @Autowired
    private PlayersService playersService;
    @Autowired
    private ClubsService clubsService;

    @GetMapping("/list")
    public String list(Model model, @RequestParam(required = false) String pname,
                       @RequestParam(required = false) Integer cid) {

        QueryWrapper<Players> queryWrapper = new QueryWrapper<>();

        // 球员姓名，如果球员姓名不为空，添加到条件中
        if(pname != null && !pname.equals("")) {
            queryWrapper.like("pname", pname);
        }

        // 所属球队，如果球队id不为空，添加到条件中
        if(cid != null) {
            queryWrapper.eq("cid", cid);
        }

        List<Players> list = playersService.list(queryWrapper);
        List<Clubs> clubsList = clubsService.list();

        model.addAttribute("list", list);
        model.addAttribute("clubsList", clubsList);
        return "list";
    }

    @GetMapping("/toAdd")
    public String toAdd(Model model) {
        List<Clubs> clubsList = clubsService.list();
        model.addAttribute("clubsList", clubsList);
        return "add";
    }


    @GetMapping("/del")
    public String delete(@RequestParam(required = true) Integer id) {
        int result = playersService.deleteById(id);  // 注意这里调用的方法是 deleteById
        if (result > 0) {
            return "redirect:/players/list";
        } else {
            return "error";
        }
    }


    @PostMapping("/add")
    public String update(@Validated @ModelAttribute Players player,
                         BindingResult bindingResult,
                         Model model) {
        if (bindingResult.hasErrors()) {
            return "error";
        }
        boolean result = playersService.save(player);
        if (result) {
            return "redirect:/players/list";
        } else {
            return "error";
        }
    }

}
